import React, { useEffect, useState } from 'react';
import styles from './index.less';
import _ from 'lodash';

import { TRDefault, TRMessage } from '#/components';
import { HttpCode } from '#/utils/contacts';
import { PageLoading } from '@/components';
import { TjChart, TjCollapse } from '@/pages/ETrade/components';

import BaseTable from '../../components/BaseTable/index.tsx';
import { chartsMap, indexMap, Doubel_yAxis_title, Doubel_yAxis_serise } from './helper';
import { forMater, _getTotalStatementEnergyPrice, _getPriceAverage } from './utils';
import { postUpdate } from './services';

export const DayContent = ({ dataSource, dataHeader, loading, error, fetchData, queryForm }) => {
  let [realData, setRealData] = useState([]); // 记录echars数据

  let echarsData = [];

  useEffect(() => {
    if (!dataSource.length) return;
    getEcharsData();
  }, [dataSource]);

  /** methods */

  const getXaxis = (data, name) => {
    const newValue = [];
    data?.map((item) => {
      newValue.push(item[name]);
    });
    return newValue;
  };

  // 获取echars图表数据
  const getEcharsData = () => {
    const data = dataSource || []; // 表格原始数据
    const dataMap = {};
    let XAXIS; // 图标X轴方向数据

    echarsData = data.slice(1);
    XAXIS = getXaxis(echarsData, 'name');
    const flatMap = Object.values(chartsMap)
      .flat()
      .map((t) => t.split('_')[0])
      .filter((t) => t); //去除空字符串

    new Set(flatMap).map((t) => {
      // if (t.includes('_')) return; //在下方计算
      dataMap[t] = forMater(echarsData, t);
    });
    //计算
    dataMap._averagePrice = _getPriceAverage(echarsData); // 价格均线

    setRealData({
      ...dataMap,
      XAXIS,
    });
  };

  /**图表配置*/
  const getChartOption = ([title, data], dataSource) => {
    const chartData = [],
      _yAxis = [{ type: 'value' }];
    dataSource.XAXIS.map((x, i) => {
      const temp = {};
      data.map((t) => {
        const a = t.split('_');
        //屏蔽同名 不同系列名
        if (a[0] && a[1]) {
          temp[t] = dataSource[a[0]][i];
          return;
        }
        temp[t] = dataSource[t][i];
      });
      chartData.push({
        ...temp,
        XAXIS: x,
      });
    });
    if (Doubel_yAxis_title.includes(title)) {
      _yAxis.push({
        type: 'value',
        splitLine: { show: false },
      });
    }
    const _series = data.map((t) => {
      const { props, ...others } = _.cloneDeep(indexMap[t]);
      if (Doubel_yAxis_title.includes(title) && Doubel_yAxis_serise.includes(t)) {
        props.yAxisIndex = 1;
      }
      return {
        dataIndex: t,
        props,
        ...others,
      };
    });

    return {
      grid: { top: 20, left: 48, right: 36, bottom: 50 },
      series: _series,
      dataset: {
        source: chartData,
        dimensions: ['XAXIS', ...data],
      },
      tooltip: {},
      legend: {},
      xAxis: [{ type: 'category' }],
      yAxis: _yAxis,
    };
  };

  const onSave = async ({ name, gatewayMeterOngridEnergy, generatorSidePowerGeneration, code }) => {
    const params = {
      date: name,
      gatewayMeterOngridEnergy: gatewayMeterOngridEnergy,
      generatorSidePowerGeneration: generatorSidePowerGeneration,
      stationId: code,
    };
    const res = await postUpdate(params);
    if (res?.statusCode === HttpCode.SUCCESS) {
      fetchData(queryForm);
    } else {
      TRMessage.error(res?.message || '系统异常');
    }
  };

  /** render */
  const _getEchartsData = () => {
    const loopData = Object.entries(chartsMap);
    if (!realData?.XAXIS) return <TRDefault type={'empty'} />;
    return (
      <div className={styles.chartsRender}>
        {loopData.map((t, i) => {
          return (
            <div
              key={i}
              style={{ height: `calc(${Math.floor(100 / loopData.length)}%)` }}
              className={styles.chartItem}
            >
              <div className={styles.chartTitle}>{t[0]}</div>
              <div style={{ height: `calc(100% - 30px)` }}>
                <TjChart group="A" option={getChartOption(t, realData)} />
              </div>
            </div>
          );
        })}
      </div>
    );
  };

  if (loading) return <PageLoading />;
  if (error) return <TRDefault type="error" message={error} />;
  if (!dataSource.length) return <TRDefault type={'empty'} />;
  return (
    <>
      <div className={styles.content}>
        <TjCollapse
          left={_getEchartsData()}
          right={
            <>
              <div className={styles.date}>现货交易日报</div>
              <div className={styles.tableScroll}>
                <BaseTable
                  props={{ tableData: dataSource, tableHead: dataHeader }}
                  onSave={onSave}
                />
              </div>
            </>
          }
        />
      </div>
    </>
  );
};
